import axios from 'axios';

// API基础URL
const API_BASE_URL = process.env.REACT_APP_API_URL || '/api/v1';

// 定义类型接口
interface User {
  id: number;
  email: string;
  firstName?: string;
  lastName?: string;
  picture?: string;
  provider: 'local' | 'google' | 'github';
}

interface LoginResponse {
  success: boolean;
  data: {
    token: string;
    refreshToken: string;
    user: User;
  };
  message: string;
}

interface RegisterResponse {
  success: boolean;
  data: {
    token: string;
    refreshToken: string;
    user: User;
  };
  message: string;
}

interface GoogleLoginResponse {
  success: boolean;
  data: {
    token: string;
    refreshToken: string;
    user: User;
  };
  message: string;
}

interface GithubLoginResponse {
  success: boolean;
  data: {
    token: string;
    refreshToken: string;
    user: User;
  };
  message: string;
}

interface RefreshTokenResponse {
  success: boolean;
  data: {
    token: string;
    refreshToken: string;
  };
  message: string;
}

interface UserInfoResponse {
  success: boolean;
  data: User;
  message: string;
}

// 配置axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token到请求头
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('accessToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理token过期和自动刷新
api.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
    
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      
      try {
        const refreshToken = localStorage.getItem('refreshToken');
        if (refreshToken) {
          const response = await axios.post(`${API_BASE_URL}/auth/refresh`, {
            refreshToken: refreshToken
          });
          
          const { token, refreshToken: newRefreshToken } = response.data.data;
          localStorage.setItem('accessToken', token);
          localStorage.setItem('refreshToken', newRefreshToken);
          
          // 重试原始请求
          originalRequest.headers.Authorization = `Bearer ${token}`;
          return api(originalRequest);
        }
      } catch (refreshError) {
        // 刷新失败，清除所有token并重定向到登录页
        authService.logout();
        window.location.href = '/login';
        return Promise.reject(refreshError);
      }
    }
    
    return Promise.reject(error);
  }
);

// 认证服务
export const authService = {
  // 用户注册
  register: async (userData: {
    firstName?: string;
    lastName?: string;
    email: string;
    password: string;
    username?: string;
  }): Promise<RegisterResponse> => {
    try {
      const response = await api.post<RegisterResponse>('/auth/register', userData);
      
      const { token, refreshToken, user } = response.data.data;
      
      // 存储tokens和用户信息
      localStorage.setItem('accessToken', token);
      localStorage.setItem('refreshToken', refreshToken);
      localStorage.setItem('user', JSON.stringify(user));
      
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.error?.message || error.response?.data?.message || '注册失败，请重试';
      throw new Error(message);
    }
  },

  // 普通登录
  login: async (email: string, password: string): Promise<LoginResponse> => {
    try {
      const response = await api.post<LoginResponse>('/auth/login', {
        email,
        password
      });
      
      const { token, refreshToken, user } = response.data.data;
      
      // 存储tokens和用户信息
      localStorage.setItem('accessToken', token);
      localStorage.setItem('refreshToken', refreshToken);
      localStorage.setItem('user', JSON.stringify(user));
      
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.error?.message || '登录失败，请重试';
      throw new Error(message);
    }
  },

  // Google登录 (使用授权码)
  loginWithGoogle: async (code: string): Promise<GoogleLoginResponse> => {
    try {
      const response = await api.post<GoogleLoginResponse>('/auth/google', {
        code: code
      });
      
      const { token, refreshToken, user } = response.data.data;
      
      // 存储tokens和用户信息
      localStorage.setItem('accessToken', token);
      localStorage.setItem('refreshToken', refreshToken);
      localStorage.setItem('user', JSON.stringify(user));
      
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.error?.message || 'Google登录失败，请重试';
      throw new Error(message);
    }
  },

  // GitHub登录
  loginWithGithub: async (code: string): Promise<GithubLoginResponse> => {
    try {
      const response = await api.post<GithubLoginResponse>('/auth/github', {
        code: code
      });
      
      const { token, refreshToken, user } = response.data.data;
      
      // 存储tokens和用户信息
      localStorage.setItem('accessToken', token);
      localStorage.setItem('refreshToken', refreshToken);
      localStorage.setItem('user', JSON.stringify(user));
      
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.error?.message || 'GitHub登录失败，请重试';
      throw new Error(message);
    }
  },

  // 刷新token
  refreshAccessToken: async (): Promise<string | null> => {
    try {
      const refreshToken = localStorage.getItem('refreshToken');
      if (!refreshToken) {
        throw new Error('没有刷新令牌');
      }

      const response = await axios.post<RefreshTokenResponse>(`${API_BASE_URL}/auth/refresh`, {
        refreshToken
      });
      
      const { token, refreshToken: newRefreshToken } = response.data.data;
      localStorage.setItem('accessToken', token);
      localStorage.setItem('refreshToken', newRefreshToken);
      
      return token;
    } catch (error) {
      authService.logout();
      return null;
    }
  },

  // 获取当前用户信息
  getCurrentUser: async (): Promise<User | null> => {
    try {
      const response = await api.get<UserInfoResponse>('/auth/me');
      const user = response.data.data;
      
      // 更新本地存储的用户信息
      localStorage.setItem('user', JSON.stringify(user));
      
      return user;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return null;
    }
  },

  // 登出
  logout: async (): Promise<void> => {
    try {
      // 调用后端登出API
      await api.post('/auth/logout');
    } catch (error) {
      console.error('后端登出失败:', error);
    } finally {
      // 清除本地存储
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      localStorage.removeItem('user');
      localStorage.removeItem('google_id');
      localStorage.removeItem('name');
      localStorage.removeItem('email');
      localStorage.removeItem('picture');
      localStorage.removeItem('credits');
    }
  },

  // 检查是否已登录
  isAuthenticated: (): boolean => {
    const token = localStorage.getItem('accessToken');
    const user = localStorage.getItem('user');
    return !!(token && user);
  },

  // 获取存储的用户信息
  getStoredUser: (): User | null => {
    try {
      const userStr = localStorage.getItem('user');
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      console.error('解析用户信息失败:', error);
      return null;
    }
  },

  // 获取access token
  getAccessToken: (): string | null => {
    return localStorage.getItem('accessToken');
  },

  // 获取refresh token
  getRefreshToken: (): string | null => {
    return localStorage.getItem('refreshToken');
  },

  // 更新存储的用户信息
  updateStoredUser: (user: User): void => {
    try {
      localStorage.setItem('user', JSON.stringify(user));
    } catch (error) {
      console.error('更新用户信息失败:', error);
    }
  },

  // 验证token是否有效
  validateToken: async (): Promise<boolean> => {
    try {
      await api.get('/auth/me');
      return true;
    } catch (error) {
      return false;
    }
  }
};

// 导出api实例供其他服务使用
export { api };

